package com.test.trans.controller;

import com.test.trans.service.LogInfoService;
import com.test.trans.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/trans")
public class UserController2 {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LogInfoService logInfoService;

//    @Transactional 作⽤:
//    @Transactional 可以⽤来修饰⽅法或类:
//            • 修饰⽅法时: 只有修饰public ⽅法时才⽣效(修饰其他⽅法时不会报错, 也不⽣效)[推荐]
//            • 修饰类时: 对 @Transactional 修饰的类中所有的 public ⽅法都⽣效

    @Transactional
    @RequestMapping("registry")
    public String registry(String name,String password){
        userInfoService.registryUser(name,password);
        log.info("注册成功");
        //将异常捕获之后在不抛出异常的情况下则不会造成事务回滚操作，事务依然进行提交
        //如果需要事务进行回滚，有以下两种方式：
        //1.重新抛出异常
        try {
            int result = 10/0;
        }catch (Exception e){
            e.printStackTrace();
        }
        //2.手动回滚事务
        //使⽤ TransactionAspectSupport.currentTransactionStatus() 得到当前的事务, 并
        //使⽤ setRollbackOnly 设置 setRollbackOnly

        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        return "注册成功";
    }

//   在Spring的事务管理中，默认只在遇到运⾏时异常RuntimeException和Error时才会回滚.
//•  如果需要回滚指定类型的异常, 可以通过rollbackFor属性来指定.
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("r1")
    public String r1(String name,String password) throws IOException {
        userInfoService.registryUser(name,password);
        log.info("注册成功");
        if (true){
            throw new  IOException();
        }
        return "注册成功";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("r2")
    public String r2(String name,String password) {
        logInfoService.insertLog(name, "用户注册");
        userInfoService.registryUser(name, password);

        return "注册成功";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("r3")
    public String r3(String name,String password){
        logInfoService.insertLog2(name,"用户注册");
        userInfoService.registryUser2(name, password);

        return "注册成功";
    }
}
